#!/bin/awk -f
# Synopsis: mktm
# reads mktm.def to get ROOTNAME, then reads rTM (raw transfer matrix)
# constructs transfer matrix with symbolic entries instead energies > sTM
BEGIN{
  fn="rTM";
  ARGC=1;
  getline<fn;
  mdim=$1;
  for(i=1;i<=mdim;i++){
    ARGC++;
    ARGV[ARGC-1]="L"i"/two.erep";
    for(j=1;j<=mdim;j++){
      getline<fn;
      sub(/\#.+$/,"");
      m[i,j]=$0;
    }
  }
}
$1 !~ /^ *\#/{
  line=$0;
  sub(/^.+\#/,"",line);
  split(line,a);
  elay=a[2];
  line=$0;
  sub(/\#.+$/,"",line);
  na=split(line,a);
#  print na,line;
  for(i=1;i<=na;i++){
    gsub(/ */,"",a[i]);
    if(a[i]!=""){
      pos=a[i];
      e2[ARGIND,pos]=elay;
      if(po[elay]==""){
	npo++; 
	mpo[npo]=elay; 
	po[elay]="L"npo;
	ss=FILENAME;
	sub(/\.erep/,"",ss);
	fpo[npo]=ss" "a[1];
      }
    }
  }
}
END{
  ftm="sTM";
  print "symbolic TM -> "ftm;
  print mdim" # dimension" > ftm;
  for(i=1;i<=mdim;i++){
    fln="L"i"/two";
    for(j=1;j<=mdim;j++){
      na=split(m[i,j],a);
      n=0;for(k=1;k<=na;k++){
	gsub(/ */,"",a[k]);
	if(a[k]!=""){n++; a[n]=a[k]};
      }
      split("",x); # clear x
      for(k=1;k<=n;k++){
	b[k]=po[e2[i,a[k]]];
	poi[e2[i,a[k]]]=poi[e2[i,a[k]]]" "i"-"j;
	x[b[k]]++;
#	printf b[k]" ";
      }
      n=0; for(k in x){n++};
      printf n"  ">>ftm;
      nn=0; for(k in x){nn++; printf x[k]"*"k>>ftm; if(nn<n){printf " ">>ftm}};
      print "  # "i,j>>ftm;
    }
  }
  print "# "npo" double-layer tilings for energy calculation";
  fnti="etil";
  fnLs="x2.L";
#  firstT=fnr"_1.two";
  firstT="L1/two";
  getline<firstT;
  print $1,$2,npo" # mktm" > fnLs;
  getline<firstT;
  print $0 >> fnLs;
  getline<firstT;
  print $0 >> fnLs;  
  close(firstT);
  printf "" > fnti;
  for(j=1;j<=npo;j++){
    split(fpo[j],a);
    print po[mpo[j]],fpo[j],poi[mpo[j]]>>fnti;
#    system("cat "a[1]" | ../poptil "a[2]" > "fnr"."po[mpo[j]]);
    system("cat "a[1]" | "udir"poptil "a[2]" -nohead >> "fnLs);
  }
  close(fnLs);
  close(fnti);
}
